package aor2.components;

import java.util.ArrayList;
import java.util.Iterator;

import aor2.common.Tracker;
import aor2.components.records.RecordSignal;
import aor2.cpu.ClockCPU;

public class Signal implements ElementIO {
	private boolean active;
	private ArrayList<ElementIO> src;
	private ArrayList<ElementIO> dst;

	private Tracker history;

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		if (this.active != active) {
			this.active = active;
			history.put(new RecordSignal(this));
		}
		this.active = active;
	}

	public Signal(boolean active) {
		super();
		this.active = active;
		src = new ArrayList<ElementIO>();
		dst = new ArrayList<ElementIO>();
		history = new Tracker();
		history.put(new RecordSignal(this));
	}

	public void addSourceElementIO(ElementIO... elementIOs) {
		for (ElementIO e : elementIOs) {
			src.add(e);
		}
	}

	public void addDestinationElementIO(ElementIO... elementIOs) {
		for (ElementIO e : elementIOs) {
			dst.add(e);
		}
	}

	@Override
	public void in() throws ElementIOException {
		Iterator<ElementIO> e = dst.iterator();
		while (e.hasNext()) {
			ElementIO elementIO = (ElementIO) e.next();
			elementIO.in();
		}
	}

	@Override
	public void out() throws ElementIOException {
		Iterator<ElementIO> e = src.iterator();
		while (e.hasNext()) {
			ElementIO elementIO = (ElementIO) e.next();
			elementIO.out();
		}
	}

	@Override
	public String toString() {
		return "Signal [active=" + active + ", src=" + src + ", dst=" + dst
				+ "\nhistory: " + history.toString() + "]";
	}

	public Tracker getHistory() {
		return history;
	}

	public void clearHistory() {
		history = new Tracker();
	}

	public void previousClk() {
		RecordSignal tmp = (RecordSignal) history.getFromTop(0);
		if (tmp != null) {
			while (((ClockCPU) (tmp).getMark()).compareTo(ClockCPU
					.getInstance()) > 0 && tmp != null) {
				history.takeFromTop();
				tmp = (RecordSignal) history.getFromTop(0);
			}
			if (tmp != null)
				//setActive(((RecordSignal) history.takeFromTop()).getValue());
				active = tmp.getValue();
		}
		
	}

}
